<template>
  <Dialog title="办理住院" :visible="visible" button-text="保存" class="two-columns" @close="handleClose" @confirm="handleConfirm">
    <!-- 办理住院 -->
    <div v-loading="loading">
      <el-form ref="ruleForm" :model="selectRow" :rules="rules" label-width="100px">
        <!-- 筛选顾客已购买的项目,检查项除外 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="顾客：" prop="customerName">
              <el-autocomplete
                v-model="selectRow.customerName"
                style="width:237.5px"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                class="el-select-y"
                :disabled="status"
                clearable
                @select="handleSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属项目：" prop="projectName">
              <el-select
                v-model="selectRow.projectName"
                filterable
                class="el-select-y"
                placeholder="请选择项目"
              >
                <!-- :disabled="!choice" -->
                <el-option
                  v-for="item in projectNameOptions"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.projectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 默认自动填写项目的主治医生 -->
            <el-form-item label="主治医生：" prop="attendingDoctorName" style="width:80%">
              <el-select v-model="selectRow.attendingDoctorName" class="el-select-y" placeholder="请选择医生" :disabled="status">
                <el-option v-for="(item,i) of doctorList" :key="i" :label="item.usrName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 至少一天 -->
            <el-form-item label="住院天数：" prop="hospitalizationDay">
              <el-input v-model="selectRow.hospitalizationDay" style="width: 237.5px;" @input="inputNumber" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="selectRow.bed" style="margin-top:18px;font-weight: bold;">已选择 {{ selectRow.bed }} 号</div>
      <!-- <ul style="box-shadow:rgba(0,0,0,.3) 0px 0px 10px;margin-top:15px"> -->
      <ul class="select-border">
        <li v-for="(item,i) in bedList" :key="i" class="room">
          <!-- :class="item.status==='启用'&&item.whetherFree==='空闲'?'kong':''" -->
          <el-button :class="item.isTrue?'kong':''" :disabled="item.status==='启用'&&item.whetherFree==='空闲'?false:true" @click="handleCheckRoom(item)">{{ item.status==='停用'?'停用':item.whetherFree }}</el-button>
          <span>{{ item.name }}</span>
        </li>
        <li class="foot" />
      </ul>
    </div>
  </Dialog>
</template>

<script>
import Dialog from "@/components/Dialog";
export default {
  components: { Dialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ruleForm: {},
      projectNameOptions: {},
      loading: false,
      state: '',
      ids: 0,
      timeout: null,
      selectRow: {},
      selectCustomer: {},
      doctorList: [], // 项目列表
      bedList: [], // 床位列表
      status: false, // 控制是否可以选择顾客或者医生
      rules: {
        customerName: [
          { required: true, message: '请输入顾客名称', trigger: 'change' },
        ],
        hospitalizationDay: [
          { required: true, message: '住院天数必填', trigger: 'blur' },
        ],
      },
      restaurants: [],
    };
  },
  watch: {
    selectRow: {
      handler() {
        this.restaurants.forEach(element => {
          // console.log(element, this.selectRow.customerName, '顾客');
          if (this.selectRow.customerName === element.name) {
            this.getProjectName(element.id);
          }
        });
      },
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  methods: {
    async loadAll() { // 根据顾客id查询已购买项目详情
      const res = await this.$api['department/consumables/customerall']();
      if (res.code === 200) {
        res.data.map(item => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      // this.selectCustomer = { customerId: item.id, appointmentSource: item.informationSources, customerSex: item.sex };
      this.selectCustomer = { customerId: item.id, customerSex: item.sex, customerCode: item.code, customerPhone: item.phone };
      Object.assign(this.selectRow, this.selectCustomer);
      if (item.id) {
        this.getProjectName(item.id);
      }
    },
    // 顾客已购项目
    async getProjectName(id) {
      // const res = await this.$api['reception/subscribe/customerIdAllByOrderList']({ customerId: id });
      const res = await this.$api['customer/customers/orderListDetails']({ customerId: id });
      console.log(res.data, '已购项目');
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    inputNumber(val) { // 住院天数最少是一天
      this.selectRow.hospitalizationDay = this.selectRow.hospitalizationDay.replace(/[^\d.]/g, ""); // 清除“数字”和“.”以外的字符
      this.selectRow.hospitalizationDay = this.selectRow.hospitalizationDay.replace(/^\./g, ""); // 验证第一个字符是数字而不是.
      this.selectRow.hospitalizationDay = this.selectRow.hospitalizationDay.replace(/\.{2,}/g, "."); // 只保留第一个. 清除多余的
      this.selectRow.hospitalizationDay = this.selectRow.hospitalizationDay.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      this.selectRow.hospitalizationDay = this.selectRow.hospitalizationDay.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3');// 只能输入两个小数
      // if (val === '') {
      //   this.selectRow.hospitalizationDay = 1;
      // }
    },
    // 选择病房
    handleCheckRoom(val) {
      this.$set(this.selectRow, 'bed', val.name);
      this.$set(this.selectRow, 'bedId', val.id);
      this.bedList.forEach((item, i) => {
        if (item.name === val.name) {
          this.$set(item, 'isTrue', true);
        } else {
          this.$set(item, 'isTrue', false);
        }
      });
    },
    addBtn(id) {
      // this.loading = true;
      this.status = false;
      this.getDoctorList();
      this.getBedList();
      this.loadAll();
      this.ids = id;
      this.$set(this.selectRow, 'hospitalizationDay', 1);
      if (!id) return false;
      this.$api[`department/inpatient/details`]({ id }).then(res => {
        if (res.code !== 200) return this.$massage.error('查询住院详情失败');
        // this.msgSuccess('查询住院详情成功');
        this.selectRow = res.data;
        this.$set(this.selectRow, 'startBedId', this.selectRow.bedId);
        this.status = true;
      });
    },
    handleClose() {
      this.$emit('update:visible', false);
      this.$emit('update:selectRow', {});
      this.$refs.ruleForm.resetFields();
      this.selectRow = {};
    },
    // 查询全部床位
    getBedList() {
      this.$api[`department/bed/pageList`]({ }).then(res => {
        this.bedList = [];
        if (res.code !== 200) return this.$massage.error('查询全部床位失败');
        this.bedList = res.data;
        this.bedList.forEach(item => {
          if (item.name === this.selectRow.bed) {
            this.$set(item, "isTrue", true);
          }
        });
        // this.msgSuccess('查询顾客成功');
      });
    },
    // 根据职位查询医生
    async getDoctorList() {
      const res = await this.$api['reception/subscribe/getAllByJobName']({ hospitalJobName: '主治医生' });
      this.doctorList = [];
      if (res.code !== 200) return this.$message.error('获取主治医生列表数据失败！');
      // this.$message.success('获取主治医生列表数据成功！');
      this.doctorList = res.data;
    },
    handleConfirm() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return;
        this.loading = true;
        this.doctorList.forEach(item => {
          if (item.id === this.selectRow.attendingDoctorName) {
            this.$set(this.selectRow, 'attendingDoctorId', item.id);
            this.$set(this.selectRow, 'attendingDoctorName', item.usrName);
          }
        });
        this.projectNameOptions.forEach(item => {
          if (item.projectId === this.selectRow.projectName) {
            this.$set(this.selectRow, 'projectName', item.projectName);
            this.$set(this.selectRow, 'projectId', item.projectId);
          }
        });
        if (this.ids) {
          this.$api[`department/inpatient/edit`]({ ...this.selectRow }).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('修改住院中心成功');
            this.handleClose();
          }).finally(() => (this.loading = false));
        } else {
          console.log(2, this.selectRow, '查询全部床位');
          this.$api[`department/inpatient/insert`]({ ...this.selectRow }).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('增加住院中心成功');
            this.handleClose();
          }).finally(() => (this.loading = false));
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
  .el-form-item .el-select{
    width: 237.5px !important;
  }
ul{
  display: flex;
  flex-wrap: wrap;
}
.room{
  display: inline-block;
  width: 8%;
  height: 70px;
  margin: 20px 10px;
  text-align: center;
  line-height: 22px;
  display: flex;
  flex-direction: column;
  color: #b3b3b3;
  >.el-button:nth-child(1){
    background: #f2f2f2;
    padding: 20px 0;
    border-radius: 8px;
    width: 100%;
    height: 50px;
  }
}
.room>button{
  border-color: #D3DFF7;
}
.foot:before{
    overflow: hidden;
    height: 0;
    clear: both;
    visibility:hidden;
    content: "";
    display: block;
}
.kong{
  color: #d3dff7;
  // background: #d3dff7;
  background: #a9c2f3 !important;
}
// .noKong{
//   color: red;
// }
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 18px !important;
}
.select-border{
  border: 1px solid #D3DFF7;
  margin-top: 10px;
  border-radius: 5px;
}
</style>
